//
//  LCVideoViewController.m
//  九酷云头条
//
//  Created by admin on 17/2/28.
//  Copyright © 2017年 admin. All rights reserved.
//

#import "LCVideoViewController.h"
#import "ChannelModel.h"
#import "ChannelLabel.h"
#import "VideoCollectionViewCell.h"

@interface LCVideoViewController () <UICollectionViewDataSource,UICollectionViewDelegate>

/// 频道标签滚动视图
@property (weak, nonatomic) IBOutlet UIScrollView *channelScrollView;
/// 新闻滚动视图
@property (weak, nonatomic) IBOutlet UICollectionView *newsCollectionView;
/// 新闻滚动视图的布局
@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *newsCollectionViewFlowLayout;
/// 频道标签模型数组
@property (nonatomic, strong) NSArray *channelModels;
/// 频道标签缓存池
@property (nonatomic, strong) NSMutableArray *labelsM;

@end

@implementation LCVideoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    /// 实例化频道标签缓存池
    _labelsM = [NSMutableArray array];

    // iOS7.0的特性 : 当滚动视图及其子类(UIScrollView/UIWebView/UITablewView/UICollectionView/UITexeView...)在自动布局时,遇到导航,里面的内容会自动的向下偏移64像素.
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [self createChannelLabels];
    
    [self setupNewsCollectionView];
    
    [self setupTitleImageView];///创建Title图片

//channelScrollView
    self.channelScrollView.showsVerticalScrollIndicator = FALSE;
    self.channelScrollView.showsHorizontalScrollIndicator = FALSE;
}
///创建Title图片
- (void)setupTitleImageView {
    UIImageView *imageView = [[UIImageView alloc] init];
    imageView.image = [UIImage imageNamed:@"title"];
    self.navigationItem.titleView = imageView;
    
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.offset(20);
    }];
}

/// 能够执行到这个方法,NewsCollectionView大小一定是正确的
- (void)viewDidAppear:(BOOL)animated {
    
    [super viewDidAppear:animated];
    
    // 把cell的大小设置成跟NewsCollectionView一般大
    self.newsCollectionViewFlowLayout.itemSize = self.newsCollectionView.bounds.size;
}
/// 创建频道标签控件 : 根据频道标签模型数组的元素个数而定的
- (void)createChannelLabels {
#pragma mark - 上面选择标题的请求
    __weak typeof(self) weakSelf = self;
    [LSZRequestResolutionDic initWithVideoChooseRequestData:^(BOOL isOk, NSString * str, LSZVideoManager * mg) {
        if (isOk == YES)
        {
            if (mg.mutMgArray.count != 0){
                [weakSelf setVidelManager:mg];
             }
        }
        else
        {
            NSString * str  = [NSString stringWithFormat:@"%@",videoChoose];
            [LSZCacheHandling initWithfindPlist:str :^(BOOL isOk, NSDictionary * diction) {
                if (isOk == YES) {
                    LSZVideoManager * manager = [[LSZVideoManager alloc]initWithVideoManager:diction];
                    if (manager.mutMgArray.count != 0){
                        [weakSelf setVidelManager:manager];
                    }
                }else{
                    [weakSelf setHubStr:str];
                }
            }];
//            if ([str isEqualToString:NoNetwork])
//            {
//
//            }else{
//                [weakSelf setHubStr:str];
//            }
        }
    }];
}
-(void)setVidelManager :(LSZVideoManager*)mg
{
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        //                    _channelModels = mg.mutArrayDic;
        self.arrayTopArray = mg.mutMgArray;
        [self.newsCollectionView reloadData];//刷新UI
        // 定义宽高
        CGFloat labelW = 80;
        CGFloat labelH = 44; // 也可以指定为父视图的高度
        CGFloat space = 25; // 间隔
        // 遍历频道标签模型数组
        for (NSInteger i = 0; i < _arrayTopArray.count; i++) {
            // 创建频道标签
            ChannelLabel *label = [ChannelLabel new];
            // 添加到父视图
            [self.channelScrollView addSubview:label];
            // 获取X值
            CGFloat labelX = labelW * i;
            // 布局
            label.frame = CGRectMake(labelX, 0, labelW, labelH);
            // 赋值
            //                        ChannelModel *model = _channelModels[i];
            //                        arrayTopArray
            LSZVideoMg * model = nil;
            model = self.arrayTopArray[i];
            NSLog(@"%@",model.cate);
            label.text = model.cate;
            // 创建点击手势
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(channelLabelTapClick:)];
            // 添加到label
            [label addGestureRecognizer:tap];
            // 开启交互
            label.userInteractionEnabled = YES;
            // 设置tag : 方便在点击时知道当前点击的是第几个
            label.tag = i;
            // 把每次创建的label,按顺序添加到容器
            [_labelsM addObject:label];
            // 把第0个label默认缩放到最大
            if (i == 0) {
                label.scale = 1.0;
            }
            // 布局
            if (i == 0) {
                [label mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.left.offset(space);
                    make.width.equalTo(label.mas_width);
                    make.height.equalTo(label.mas_height);
                    make.centerY.equalTo(self.channelScrollView.mas_centerY);
                }];
            }else{
                ChannelLabel *lastLabel = _labelsM[i - 1];
                [label mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.left.equalTo(lastLabel.mas_right).offset(space);
                    make.width.equalTo(label.mas_width);
                    make.height.equalTo(label.mas_height);
                    make.centerY.equalTo(self.channelScrollView.mas_centerY);
                }];
            }
        }
        // 设置滚动视图的滚动范围 : height = 0 表示横向滚动
         [self.channelScrollView layoutIfNeeded];
        ChannelLabel *endLabel = _labelsM.lastObject;
        CGFloat channelContentSizeWidth = CGRectGetMaxX(endLabel.frame) > ScreenWidth ? CGRectGetMaxX(endLabel.frame) : ScreenWidth ;
        // 设置滚动视图的滚动范围 : height = 0 表示横向滚动
        self.channelScrollView.contentSize = CGSizeMake(channelContentSizeWidth+space, 0);
    }];
}
-(void)setHubStr :(NSString *)str
{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeText;//枚举类型不同的效果
    //    hud.mode = MBProgressHUDModeCustomView;
    hud.label.text= [NSString stringWithFormat:@"%@",str];
    [self performSelector:@selector(hiddenMBAction) withObject:nil afterDelay:1.0];
}
-(void)hiddenMBAction
{
    [MBProgressHUD hideHUDForView:self.view animated:YES];
}
/// 设置newsCollectionView
- (void)setupNewsCollectionView {
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 0.3)];
    view.backgroundColor = [UIColor colorWithWhite:0.8 alpha:1];
    [self.newsCollectionView addSubview:view];

    // 设置数据源/代理
    self.newsCollectionView.dataSource = self;
    self.newsCollectionView.delegate = self;
    // 设置分页效果
    self.newsCollectionView.pagingEnabled = YES;
    // 禁用弹簧效果
    self.newsCollectionView.bounces = NO;
    // 设置滚动方向
    self.newsCollectionViewFlowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    // 设置最小间距
    self.newsCollectionViewFlowLayout.minimumLineSpacing = 0;
    self.newsCollectionViewFlowLayout.minimumInteritemSpacing = 0;
    
}

/// 频道标签手势点击事件
- (void)channelLabelTapClick:(UITapGestureRecognizer *)tap {
    
    // 1.把选中的频道标签居中
    // 1.1 需要找到点击的是哪个标签
    ChannelLabel *tapLabel = (ChannelLabel *)tap.view;
    // 1.2 计算选中的标签居中时,需要滚动的距离
    CGFloat offsetX = tapLabel.center.x - self.view.bounds.size.width*0.5;
    
    // 1.3 限制最大和最小滚动范围
    CGFloat minOffset = 0;
    CGFloat maxOffset = self.channelScrollView.contentSize.width - self.view.bounds.size.width;
    if (offsetX < minOffset) {
        offsetX = minOffset;
    }
    if (offsetX > maxOffset) {
        offsetX = maxOffset;
    }
    
    // 1.4 获取需要滚动到的点
    CGPoint point = CGPointMake(offsetX, 0);
    // 1.5 频道滚动视图滚动到标签居中的位置
    [self.channelScrollView setContentOffset:point animated:YES];
    
    // 2.新闻视图滚动到对应的item
    // 2.1 获取需要滚动到的item的角标
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:tapLabel.tag inSection:0];
    // 2.2 滚动到指定的item
    [self.newsCollectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    
    // 遍历所有的label,如果是点击的那个就设置最大缩放比,如果不是点击的那个就把缩放比设置为最小
    for (NSInteger i = 0; i < _labelsM.count; i++) {
        
        // 取出所有的label
        ChannelLabel *label = _labelsM[i];
        // 判断取出的label是否是选中的label,如果是就设置最大缩放比
        if (i == tapLabel.tag) {
            label.scale = 1.0;
        } else {
            label.scale = 0.0;
        }
    }

}

/// 当新闻滚动视图滚动结束后,频道标签居中
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    if (scrollView == self.channelScrollView/**假如是标签视图就不做变化*/) {
        return;
    }
    
    // 计算当前滚动到第几个角标
    NSInteger index = scrollView.contentOffset.x / self.view.bounds.size.width;
    
    // 获取滚动新闻视图时,对应的标签
    ChannelLabel *label = _labelsM[index];
    
    // 计算当滚动新闻视图时,对应的标签居中时需要滚动的距离
    CGFloat offsetX = label.center.x - self.view.bounds.size.width*0.5;
    
    // 限制最大和最小 滚动范围
    CGFloat minOffset = 0;
    CGFloat maxOffset = self.channelScrollView.contentSize.width - self.view.bounds.size.width;
    if (offsetX < minOffset) {
        offsetX = minOffset;
    }
    if (offsetX > maxOffset) {
        offsetX = maxOffset;
    }
    
    // 获取居中时需要滚动到的点
    CGPoint point = CGPointMake(offsetX, 0);
    // 滚动新闻视图时,把对应的标签居中
    [self.channelScrollView setContentOffset:point animated:YES];
}

/// 监听实时滚动,实时缩放
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == self.channelScrollView/**假如是标签视图就不做变化*/) {
        return;
    }
    NSInteger index = scrollView.contentOffset.x / self.view.bounds.size.width;
    for (int i = 0; i<_labelsM.count; i++) {
        ChannelLabel *leftLabel = _labelsM[i];
        if (i == index) {
            leftLabel.scale = 1;
        }else{
            leftLabel.scale = 0;
        }
    }
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    // 频道标签有多少个就一一对应多少个cell
    return _arrayTopArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    // 这行代码执行完,就要执行awakeFromNib

    VideoCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"VideoCollectionViewCell" forIndexPath:indexPath];
    [self addChildViewController:cell.videoVC];
    // 获取NewsCollectionViewCell对应的频道标签对应的模型
//    ChannelModel *model = _channelModels[indexPath.item];
    LSZVideoMg * model = nil;
    model = self.arrayTopArray[indexPath.item];
    // 拼接新闻URL
    NSString *cid = [NSString stringWithFormat:@"%@",model.id_id];
    // 把拼接好的新闻地址传给cell
    cell.cid = cid;
    
 
    return cell;
}


@end
